using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Kona.Infrastructure;
using System.Web.Security;
using Kona.Model;
using System.Net;
using System.Xml.Linq;

namespace Kona.Web.App.Controllers
{
    public class AuthenticationController : KonaController
    {

        IAuthenticationService _authService;
        ICMSRepository _cmsRepository;
        ICustomerRepository _customerRepository;
        IObjectStore _objectStore;

        public AuthenticationController(ICustomerRepository customerRepository,
            ICMSRepository cmsRepository,
            IObjectStore objectStore,
            IAuthenticationService authService) : base(customerRepository,objectStore,cmsRepository) {
            _authService = authService;
            _cmsRepository = cmsRepository;
            _objectStore = objectStore;
            _customerRepository = customerRepository;

        }

        public ActionResult Login() {


            string login = Request.Form["username"];
            string password = Request.Form["password"];
            string remember = Request.Form["rememberMe"];
            bool setCookie = false;
            if (!string.IsNullOrEmpty(remember))
                setCookie = remember == "true";

            if (!String.IsNullOrEmpty(login) && !String.IsNullOrEmpty(password)) {
                bool isValid = _authService.IsValidLogin(login, password);

                //log them in 
                if (isValid) {
                    if (setCookie)
                        FormsAuthentication.SetAuthCookie(login, true);
                    return AuthAndRedirect(login, login);
                }
            }
            return View();


        }

        public ActionResult ReceiveToken(string token) {

            //you'll want to replace this with your own :)
            string parameters = String.Format("apiKey={0}&token={1}&format=xml", this.SiteData.RPXAPIKey, token);
            string response;
            using (var w = new WebClient()) {
                response = w.UploadString("https://rpxnow.com/api/v2/auth_info", parameters);
            }
            var xmlResponse = XDocument.Parse(response);
            var userProfile = (from x in xmlResponse.Descendants("profile")
                               select new
                               {
                                   id = x.Element("identifier").Value,
                                   userName = (string)x.Element("preferredUsername") ?? "No Preferred Username",
                                   displayname = (string)x.Element("displayName") ?? "No Display Name",
                                   email = (string)x.Element("email") ?? "No Email"
                               }).SingleOrDefault();
            //We store the unique ID for that user in the FormsAuth additional data. 
            // That's the Users GUID, for all intents.
            //hopefully we have something...
            if (userProfile != null) {
                string friendly=userProfile.userName;
                if (!string.IsNullOrEmpty(userProfile.displayname))
                    friendly = userProfile.displayname;

                //We store the unique ID for that user in the FormsAuth additional data. 
                return AuthAndRedirect(userProfile.id, friendly);
            } else {
                return RedirectToAction("Index", "Home");
            }
        }
        ActionResult AuthAndRedirect(string userName, string friendlyName) {

            string returnUrl = Request["ReturnUrl"];
            SetCookies(userName, friendlyName);

            if (!String.IsNullOrEmpty(returnUrl)) {
                return Redirect(returnUrl);
            } else {
                return RedirectToAction("Index", "Home");
            }
        }

        void SetCookies(string userName, string friendlyName) {
            Response.Cookies["shopper"].Value = userName;
            Response.Cookies["shopper"].Expires = DateTime.Now.AddDays(30);
            Response.Cookies["shopper"].HttpOnly = true;

            Response.Cookies["shopperName"].Value = friendlyName;
            Response.Cookies["shopperName"].Expires = DateTime.Now.AddDays(30);
            Response.Cookies["shopperName"].HttpOnly = true;

            FormsAuthentication.SetAuthCookie(userName, true);
        }




        public ActionResult Logout() {
            Response.Cookies["shopper"].Value = null;
            Response.Cookies["shopper"].Expires = DateTime.Now.AddDays(-1);

            Response.Cookies["shopperName"].Value = null;
            Response.Cookies["shopperName"].Expires = DateTime.Now.AddDays(-1);

            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");

        }

    }
}
